package com.ww.trysomething.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@RestController
public class HttpContextController {
    @GetMapping("context")
    void httpContext(HttpServletRequest request, HttpServletResponse response) {
        try {
            //request.getClass()
            int len = request.getContentLength();
            //获取HTTP请求的输入流
            InputStream is = request.getInputStream();
            //已HTTP请求输入流建立一个BufferedReader对象
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            //读取HTTP请求内容
            String buffer = null;
            StringBuffer sb = new StringBuffer();
            while ((buffer = br.readLine()) != null) {
                //在页面中显示读取到的请求参数
                sb.append(buffer + "\n");
            }
            System.out.println("接收post发送原始数据:\n" + sb.toString().trim());
            PrintWriter out = response.getWriter();
            StringBuffer stringBuffer = new StringBuffer("OK");
            out.write(stringBuffer.toString());
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println("error" + e);
        }
    }
}
